/**
 * author:Administrator
 * date:2016/3/19
 * desc: coupon 领取
 * -> 源事件 CouponLog: CouponApplied
 * -> on CouponApplied => Coupon: 修改自己的数量( finish ),pub event: couponReserved or couponLacking
 * ->on couponReserved => CouponLog: couponReserved( finish )
 * ->on couponLacking => CouponLog: couponLacking( finish )
 */

'use strict';

let Saga = require('../../lib/Saga.js');
let events = require('./domainEvent.js');
let CouponRepo = require('../model_cmd/coupon/CouponRepo.js');
let Coupon = require('../model_cmd/coupon/CouponMjs.js');

let CouponLogRepo = require('../model_cmd/couponLog/CouponLogRepo.js');
let CouponLog = require('../model_cmd/couponLog/CouponLog.js');

let debug = console.log.bind(console);

class CouponApplySaga extends Saga {
  constructor(customerId, coupon) {
    super();
    console.log(this.constructor.name + ' set up...');
    super.subscribe(events.ENUM_EVENT.couponApplied);
    super.subscribe(events.ENUM_EVENT.couponReserved);
    this.customerId = customerId;
    this.coupon = coupon;
  }

  // 启动
  * start() {
    let couponLog = CouponLog.freshNew({
      customerId: this.customerId,
      couponId: this.coupon.id,
      money: this.coupon.money
    });
    yield couponLog.store(this.sagaId);
  }

  * couponApplied(event) {
    debug('handle event ', event.type);
    // coupon 数量减少
    let couponLog = event.data;
    let couponPojo = yield CouponRepo.find(couponLog.couponId);
    let coupon = Coupon.rebuild(couponPojo);
    yield coupon.reserve(couponLog, this.sagaId);
  }

  * couponReserved(event) {
    debug('handle event ', event.type);
    // couponLog 状态变化
    let couponLog = event.data;
    yield couponLog.couponReserved(this.sagaId);

    this._end(couponLog);
  }

  * couponLacking(event) {
    debug('handle event ', event.type);
    // couponLog 状态变化
    let couponLog = event.data;
    yield couponLog.couponLacking(this.sagaId);

    this._end(null);
  }

}

module.exports = CouponApplySaga;